<template>
	<view class="container">
		<view class="body">
			<up-sticky bgColor="#fff">
				<up-tabs :list="tapTitleList" v-model:current="currentTab" @change="switchTab"></up-tabs>
				<view class="search">
					<up-search placeholder="输入设备编号" v-model="sbbhSearchWord" @search="sbbhSearch" @custom="sbbhSearch"
						@clickIcon="scanQRCode" searchIcon="scan" scrollable="false" :show-action="false" shape="round"
						height="36" bgColor="#fff" placeholderColor="#999" searchIconColor="#252B93"
						color="#333"></up-search>
				</view>
			</up-sticky>


			<view class="task-list">
				<view class="task-item" @tap="goToDetail(item.id,item.checkDate)" v-for="(item) in ListData"
					:key="item.plandateid">
					<view class="task-info">
						<view class="device-name">{{ item.sbmc }}</view>
						<view class="device-code">设备编号：{{ item.sbbh }}</view>
						<view class="location">使用部门：{{ item.bmmc }}</view>
						<view class="location" v-if="currentTab===1||currentTab===2">点检日期：{{ item.checkDate }}</view>
						<view class="location" v-if="currentTab===1||currentTab===2">
							点检人&nbsp&nbsp&nbsp：{{ item.spotCheckBy }}</view>
					</view>
					<view
						style="display: flex;flex-direction: column;height: 80px;min-width: 80px;justify-content: center; align-items: center;">
						<view class="task-status" v-if="currentTab===1||currentTab===2">
							<view :class="item.errorFlag==0?'check-pass':'check-error'">
								{{ item.errorFlag==0?item.quickConfirmFlag==1?'正常未检':'正常已检':item.quickConfirmFlag==1?'异常未检':'异常已检' }}
							</view>
						</view>
						<view style="flex:1">
							<view class="task-button" @click.native.stop="confirmQuick(item.plandateid)"
								v-if="(currentTab===1||currentTab===2)&&item.errorFlag===0&&item.quickConfirmFlag ===1">
								<view class="action-text">一键确认</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import ScanBtn from "../../../components/scabBtn/scanBtn.vue";

	export default {
		components: {
			ScanBtn
		},
		data() {
			return {
				//搜索词
				sbbhSearchWord: '',
				tapTitleList: [{
						name: "点检员",
						disabled: true
					},
					{
						name: "班组长",
						disabled: true
					},
					{
						name: "设备员",
						disabled: true
					}
				],
				currentTab: 0, // 当前选中的tab，默认 点检员反馈
				ListData: [], // 当前页面列表
				ListDataTemp: [], // 接口查询结果
				//分页信息
				pageIndex: 1,
				pageSize: 10,
				total: 0,
				userId: "",
				userPic: "",
			};
		},
		onLoad() {
			/*根据用户配置的权限显示tab页签*/
			//包含班组长权限 显示 点检员反馈/班组长确认
			if (this.$userPerssion.bzzPermission()) {
				this.tapTitleList = this.tapTitleList.map(item => {
					if (item.name === '点检员' || item.name === '班组长') {
						return {
							...item,
							disabled: false
						};
					}
					return item;
				});
			}
			//包含权限 显示 设备员审核
			if (this.$userPerssion.sbkPermission()) {
				this.tapTitleList = this.tapTitleList.map(item => {
					if (item.name === '设备员') {
						return {
							...item,
							disabled: false
						};
					}
					return item;
				});
			}
			// 页面加载时 初始化 当前用户历史处理过的设备列表
			this.loadHistorySbListByTab();
			this.userId = this.$commonUnits.getUserId();
			this.userPic = uni.getStorageSync('user_pic');
			uni.$on('getListData', (data) => {
				// console.log("data",data);
				if (this.currentTab === 0)
					return;
				//一键确认成功后隐藏一键确认按钮
				this.ListData.forEach(item => {
					if (item.plandateid === data.plandateid) {
						item.quickConfirmFlag = data.quickConfirmFlag;
					}
				})
			})
		},
		methods: {
			//搜索功能
			async sbbhSearch() {
				this.pageIndex = 1;
				this.pageSize = 10;
				this.total = 0;
				this.ListData = [];
				try {
					await this.getListData();
					this.ListData = [...this.ListDataTemp];
				} catch (e) {
					console.error('加载数据失败:', error);
				}
			},

			scanQRCode() {
				uni.scanCode({
					success: (res) => {
						this.sbbhSearchWord = res.result;
						this.sbbhSearch();
					},
					fail: (err) => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 切换Tab
			switchTab(tab) {
				//当前标签页index
				this.currentTab = tab.index;
				// 重新加载对应数据
				this.loadHistorySbListByTab();
			},

			// 切换页签获取 当前用户 最近 反馈过/确认过的 设备历史列表
			async loadHistorySbListByTab() {
				//重置一下分页信息
				this.pageIndex = 1;
				this.pageSize = 10;
				this.total = 0;
				this.sbbhSearchWord = "";
				this.$set(this, 'ListData', []);
				this.$set(this, 'ListDataTemp', []);
				// console.log('查询前',this.ListData);
				//获取列表数据
				try {
					await this.getListData();
					this.$set(this, 'ListData', this.ListDataTemp);
					// console.log('查询后',this.ListData,this.ListDataTemp);
				} catch (e) {
					console.error('加载数据失败:', error);
				}
			},

			//获取列表数据
			async getListData() {
				try {
					const res = await this.$commonUnits.postRequest(
						"sbby.spotcheckmobilebiz.getUserRencentActionSbListByPage.mobile", {
							userId: this.$commonUnits.getUserId(),
							type: this.currentTab,
							searchWord: this.sbbhSearchWord,
							pageIndex: this.pageIndex,
							pageSize: this.pageSize,
							userPic: this.userPic,
						}
					);

					if (res.code === '1') {
						this.ListDataTemp = res.res.list;
						this.total = res.res.total;

						// 分页处理逻辑
						if (this.pageIndex === 1) {
							this.ListData = [...this.ListDataTemp];
						} else {
							this.ListData = [...this.ListData, ...this.ListDataTemp];
						}
					}
				} catch (error) {
					console.error('请求失败:', error);
					throw error; // 抛出错误供上层捕获
				}
			},

			//加载下一页
			async loadNextPage() {
				//超出总条数不加载
				if (this.ListData.length >= this.total) return;

				this.pageIndex++;
				try {
					await this.getListData();
				} catch (error) {
					this.pageIndex--; // 回滚页码
					console.error('加载更多失败:', error);
				}
			},

			// 跳转到点检详情页
			goToDetail(id, checkDate) {
				uni.navigateTo({
					url: `/pagesOne/pages/inspection/detail?id=${id}&type=${this.currentTab}&checkdate=${checkDate}`,
				});
			},

			/*    handleScan(e) {
			      console.log('扫码结果：', e);
			    },*/

			confirmQuick(plandateid) {
				if (this.currentTab === 1) {
					this.$commonUnits.postRequest("sbby.spotcheckmobilebiz.bzzSpotCheckConfirm.mobile", {
						id: plandateid,
						userid: this.userId,
					}).then(item => {
						uni.showToast({
							title: '一键确认成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								//一键确认成功后隐藏一键确认按钮
								this.ListData.forEach(item => {
									if (item.plandateid === plandateid) {
										item.quickConfirmFlag = 0;
									}
								})
							}
						});
					})
				}
				if (this.currentTab === 2) {
					this.$commonUnits.postRequest("sbby.spotcheckmobilebiz.sbySpotCheckConfirm.mobile", {
						id: plandateid,
						userid: this.userId,
					}).then(item => {
						uni.showToast({
							title: '一键审核成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								//一键确认成功后隐藏一键确认按钮
								this.ListData.forEach(item => {
									if (item.plandateid === plandateid) {
										item.quickConfirmFlag = 0;
									}
								})
							}
						});
					})
				}
			}
		},
		//触底加载下一页
		onReachBottom() {
			//加载下一页
			this.loadNextPage();
		}
	};
</script>

<style lang='scss' scoped>
	.body {
		height: 100%;
		padding-bottom: 20rpx;
	}

	.search {
		padding-top: 10px;
		background-color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(2rpx);
		}

		:deep(.u-search__content) {
			border-radius: 50rpx !important;
			border: 2rpx solid #1890ff !important;
			box-shadow: 0 2rpx 8rpx rgba(37, 43, 147, 0.1);
			border: 1rpx solid #eee;

			&:focus-within {
				border-color: #1890ff !important;
				box-shadow: 0 2rpx 12rpx rgba(37, 43, 147, 0.2);
			}
		}

		:deep(.u-search__content__input) {
			font-size: 14px;
			padding-left: 20rpx;
		}

		:deep(.u-icon__icon) {
			font-size: 18px !important;
		}
	}

	.task-list {
		padding: 10rpx 20rpx;
	}

	.task-item {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.device-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 12rpx;
	}

	.device-code,
	.location {
		min-width: 160rpx;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.task-status {
		flex: 1;
	}

	.check-pass {
		text-align: right;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 12rpx;
	}

	.check-error {
		text-align: right;
		font-size: 32rpx;
		font-weight: bold;
		color: #ff0000;
		margin-bottom: 12rpx;
	}

	.task-button {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		background: #f6ffed;
		border-radius: 4rpx;
		border: 1rpx solid #52c41a;
		cursor: pointer;
	}

	.action-text {
		font-size: 24rpx;
		color: #52c41a;
	}
</style>